<template>
  <div class="chart-settings">
    <a-form layout="vertical">
      <!-- 图表标题设置 -->
      <a-form-item label="标题">
        <a-input v-model:value="localOptions.title.text" placeholder="请输入图表标题" />
      </a-form-item>
      
      <a-form-item label="显示标题">
        <a-switch v-model:checked="localOptions.title.show" />
      </a-form-item>
      
      <!-- 漏斗图设置 -->
      <a-divider>漏斗图设置</a-divider>
      
      <a-form-item label="漏斗宽度">
        <a-input-number 
          v-model:value="funnelWidth"
          :min="10" 
          :max="100"
          :formatter="(value: number) => `${value}%`"
          :parser="(value: string) => value.replace('%', '')"
          style="width: 100%"
          @change="updateFunnelSize"
        />
      </a-form-item>
      
      <a-form-item label="漏斗方向">
        <a-select v-model:value="localOptions.series[0].sort" @change="emitUpdate">
          <a-select-option value="ascending">升序（小到大）</a-select-option>
          <a-select-option value="descending">降序（大到小）</a-select-option>
          <a-select-option value="none">无序（原始顺序）</a-select-option>
        </a-select>
      </a-form-item>
      
      <a-form-item label="底部对齐">
        <a-radio-group v-model:value="localOptions.series[0].orient" @change="emitUpdate">
          <a-radio-button value="vertical">垂直</a-radio-button>
          <a-radio-button value="horizontal">水平</a-radio-button>
        </a-radio-group>
      </a-form-item>
      
      <a-form-item label="数值显示">
        <a-radio-group v-model:value="labelPosition" @change="updateLabelPosition">
          <a-radio-button value="inside">内部</a-radio-button>
          <a-radio-button value="outside">外部</a-radio-button>
          <a-radio-button value="none">不显示</a-radio-button>
        </a-radio-group>
      </a-form-item>
      
      <a-form-item label="显示图例">
        <a-switch v-model:checked="localOptions.legend.show" @change="emitUpdate" />
      </a-form-item>
      
      <!-- 数据项设置 -->
      <a-divider>数据项</a-divider>
      
      <div v-for="(item, index) in localOptions.series[0].data" :key="index" class="data-item">
        <a-row :gutter="[16, 0]">
          <a-col :span="10">
            <a-form-item :label="`名称 ${index + 1}`">
              <a-input v-model:value="item.name" placeholder="请输入名称" @change="emitUpdate" />
            </a-form-item>
          </a-col>
          <a-col :span="10">
            <a-form-item :label="`数值 ${index + 1}`">
              <a-input-number 
                v-model:value="item.value" 
                style="width: 100%"
                @change="emitUpdate"
              />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label=" " class="delete-btn-container">
              <a-button 
                type="primary" 
                danger 
                @click="removeDataItem(index)"
                shape="circle"
              >
                <delete-outlined />
              </a-button>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item :label="`自定义颜色 ${index + 1}`">
          <a-input 
            :value="getSeriesItemColor(index)"
            placeholder="如: #1890ff" 
            :addon-before="'颜色'"
            @change="(e: Event) => updateSeriesItemColor(index, (e.target as HTMLInputElement).value)"
          />
        </a-form-item>
      </div>
      
      <a-divider></a-divider>
      
      <a-button type="dashed" block @click="addDataItem">
        <plus-outlined /> 添加数据项
      </a-button>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue';

const props = defineProps({
  options: {
    type: Object,
    required: true
  }
});

const emit = defineEmits(['update:options']);

// 本地存储options，用于编辑
const localOptions = ref<any>({
  title: {
    text: '',
    show: false
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    show: true,
    data: []
  },
  series: [
    {
      name: '漏斗图',
      type: 'funnel',
      width: '80%',
      sort: 'descending',
      orient: 'vertical',
      label: {
        show: true,
        position: 'inside'
      },
      emphasis: {
        label: {
          fontSize: 20
        }
      },
      data: [
        { value: 100, name: '访问' },
        { value: 80, name: '咨询' },
        { value: 60, name: '订单' },
        { value: 40, name: '付款' },
        { value: 20, name: '成交' }
      ]
    }
  ],
  color: [] // 自定义颜色
});

// 漏斗图宽度
const funnelWidth = ref(80);
// 标签位置
const labelPosition = ref('inside');

// 更新漏斗图大小
const updateFunnelSize = () => {
  localOptions.value.series[0].width = `${funnelWidth.value}%`;
  emitUpdate();
};

// 更新标签位置
const updateLabelPosition = () => {
  if (labelPosition.value === 'none') {
    localOptions.value.series[0].label.show = false;
  } else {
    localOptions.value.series[0].label.show = true;
    localOptions.value.series[0].label.position = labelPosition.value;
  }
  emitUpdate();
};

// 获取数据项颜色
const getSeriesItemColor = (index: number) => {
  const item = localOptions.value.series[0].data[index];
  if (item && item.itemStyle && item.itemStyle.color) {
    return item.itemStyle.color;
  }
  return '';
};

// 更新数据项颜色
const updateSeriesItemColor = (index: number, color: string) => {
  const item = localOptions.value.series[0].data[index];
  if (!item) return;

  if (!item.itemStyle) {
    item.itemStyle = { color: '' };
  }
  
  item.itemStyle.color = color;
  emitUpdate();
};

// 添加数据项
const addDataItem = () => {
  const newValue = localOptions.value.series[0].data.length > 0 
    ? localOptions.value.series[0].data[localOptions.value.series[0].data.length - 1].value / 2 
    : 100;
  
  localOptions.value.series[0].data.push({
    value: newValue,
    name: `新数据项${localOptions.value.series[0].data.length + 1}`
  });
  
  // 更新图例数据
  if (localOptions.value.legend && localOptions.value.legend.data) {
    localOptions.value.legend.data.push(`新数据项${localOptions.value.series[0].data.length}`);
  }
  
  emitUpdate();
};

// 移除数据项
const removeDataItem = (index: number) => {
  localOptions.value.series[0].data.splice(index, 1);
  
  // 同时更新图例和颜色数组
  if (localOptions.value.legend && localOptions.value.legend.data && localOptions.value.legend.data.length > index) {
    localOptions.value.legend.data.splice(index, 1);
  }
  
  if (localOptions.value.color && localOptions.value.color.length > index) {
    localOptions.value.color.splice(index, 1);
  }
  
  emitUpdate();
};

// 向父组件发送更新的options
const emitUpdate = () => {
  emit('update:options', localOptions.value);
};

// 初始化
onMounted(() => {
  // 深拷贝props的options
  if (props.options) {
    localOptions.value = JSON.parse(JSON.stringify(props.options));
    
    // 确保必要的属性存在
    if (!localOptions.value.title) {
      localOptions.value.title = { text: '', show: false };
    }
    
    if (!localOptions.value.legend) {
      localOptions.value.legend = { show: true, data: [] };
    } else if (!localOptions.value.legend.data) {
      localOptions.value.legend.data = [];
    }
    
    if (!localOptions.value.series || !localOptions.value.series.length) {
      localOptions.value.series = [{
        name: '漏斗图',
        type: 'funnel',
        width: '80%',
        sort: 'descending',
        orient: 'vertical',
        label: {
          show: true,
          position: 'inside'
        },
        data: []
      }];
    } else {
      // 确保系列有必要的属性
      if (!localOptions.value.series[0].label) {
        localOptions.value.series[0].label = { show: true, position: 'inside' };
      }
    }
    
    // 初始化宽度
    const width = localOptions.value.series[0].width;
    if (typeof width === 'string' && width.endsWith('%')) {
      funnelWidth.value = parseInt(width, 10);
    } else {
      funnelWidth.value = 80;
    }
    
    // 初始化标签位置
    if (!localOptions.value.series[0].label.show) {
      labelPosition.value = 'none';
    } else {
      labelPosition.value = localOptions.value.series[0].label.position || 'inside';
    }
    
    // 同步图例数据
    if (localOptions.value.legend && localOptions.value.legend.data) {
      // 确保图例数据与实际数据项一致
      localOptions.value.legend.data = localOptions.value.series[0].data.map((item: any) => item.name);
    }
  }
});

// 监听props.options变化
watch(() => props.options, (newOptions) => {
  if (newOptions) {
    localOptions.value = JSON.parse(JSON.stringify(newOptions));
    
    // 更新宽度
    const width = localOptions.value.series[0].width;
    if (typeof width === 'string' && width.endsWith('%')) {
      funnelWidth.value = parseInt(width, 10);
    } else {
      funnelWidth.value = 80;
    }
    
    // 更新标签位置
    if (!localOptions.value.series[0].label.show) {
      labelPosition.value = 'none';
    } else {
      labelPosition.value = localOptions.value.series[0].label.position || 'inside';
    }
  }
}, { deep: true });
</script>

<style scoped>
.chart-settings {
  padding: 10px;
}

.data-item {
  padding: 10px;
  margin-bottom: 12px;
  border: 1px dashed #ddd;
  border-radius: 4px;
}

.delete-btn-container {
  display: flex;
  justify-content: center;
  align-items: flex-end;
  height: 100%;
}
</style> 